package cc.android.testapp;

import android.app.Activity;
import android.app.Application;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.widget.Toast;

import cc.android.testapp.cfg.ConfigHelper;
import cc.android.testapp.util.CLog;
import cc.android.testapp.xp.hooker.adblock.util.ADBCfg;
import cc.commons.util.StringUtil;

public class TestApp extends Application implements TAContentProvider.TAReslove, Application.ActivityLifecycleCallbacks {

    public static final String PATH_TOAST_MSG = "/PATH_TOAST_MSG";
    private static final String KEY_ACT_CLASS = "KEY_ACT_CLASS";
    private static final String KEY_TOAST_MSG = "KEY_TOAST_MSG";
    private static final String[] TOAST_KEYS = {KEY_ACT_CLASS, KEY_TOAST_MSG};
    private Activity mFGAct = null;

    @Override
    public void onCreate() {
        super.onCreate();

        registerActivityLifecycleCallbacks(this);

        ConfigHelper.registerResolve();
        CLog.registerResolve();
        ADBCfg.registerResolve();
        TAContentProvider.registerReslove(PATH_TOAST_MSG, this);
    }

    @Override
    public String handleRequest(String pPName, String pType, Uri pUri) {
        if (PATH_TOAST_MSG.equals(pType)) {
            if (mFGAct != null && mFGAct.getClass().getName().equals(pUri.getQueryParameter(KEY_ACT_CLASS))) {
                new Handler(Looper.getMainLooper()).post(()->
                Toast.makeText(mFGAct, StringUtil.getTail(pPName) + ": " + pUri.getQueryParameter(KEY_TOAST_MSG)
                        , Toast.LENGTH_SHORT).show());
            }
        }
        return "200";
    }

    /**
     * 远端发送Toast到指定Activity,仅在该Activity在前台显示时,才会显示该Toast
     *
     * @param pActClazz 发送到哪个Activity
     * @param pMsg      要发送的消息
     */
    public static void sendRemoteToast(Class<? extends Activity> pActClazz, String pMsg) {
        ConfigHelper.resolveConfig(PATH_TOAST_MSG, TOAST_KEYS, pActClazz.getName(), pMsg);
    }

    @Override
    public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {

    }

    @Override
    public void onActivityStarted(@NonNull Activity activity) {

    }

    @Override
    public void onActivityResumed(@NonNull Activity activity) {
        this.mFGAct = activity;
    }

    @Override
    public void onActivityPaused(@NonNull Activity activity) {
        this.mFGAct = null;
    }

    @Override
    public void onActivityStopped(@NonNull Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(@NonNull Activity activity) {

    }
}
